package com.gather.service.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.common.cache.Cache;
import com.common.constant.SnatchConstant;
import com.common.dto.SnatchItem;
import com.common.dto.SnatchTask;
import com.common.dto.SnatchVersion;
import com.common.utils.CacheUtil;
import com.gather.service.AccountService;
import com.gather.service.LoggerService;
import com.gather.service.WorkService;
import com.gather.system.AccountData;
import com.work.service.SnatchControl;
import com.work.service.SnatchService;
import com.work.vo.SnatchData;
import com.work.vo.ThirdInfo;

@Service
public class WorkServiceImpl implements WorkService {

	protected Logger logger = Logger.getLogger(WorkServiceImpl.class);

	private ConcurrentMap<String, ConcurrentHashMap<String,SnatchThread>> snatchWorkMap = new ConcurrentHashMap<String, ConcurrentHashMap<String,SnatchThread>>();// 每个抓取线程版本号内存队列

	@Autowired
	private AccountService accountManageService;
	
	@Autowired
	private Cache cache;
	
	@Autowired
	private LoggerService loggerService;
	
	
	@Override
	public int snatchTask(SnatchTask snatchTask,SnatchItem snatchItem,int status) {
		ConcurrentHashMap<String,SnatchThread> webSnatchs = snatchWorkMap.get(snatchTask.getWebCode());
		if(null == webSnatchs){
			webSnatchs = new ConcurrentHashMap<String,SnatchThread>();
			snatchWorkMap.put(snatchTask.getWebCode(), webSnatchs);
		}
		
		if (webSnatchs.get(snatchTask.getTaskCode()) != null) {
			return -1;
		}
		
		if(1 == status){
			SnatchThread snatchThread = new SnatchThread();
			snatchThread.init(snatchTask);
			snatchThread.start();
			webSnatchs.put(snatchTask.getTaskCode(), snatchThread);
			snatchItem.setDescribe("采集系统启动成功!");
			
		}else{
			SnatchThread snatchThread = webSnatchs.get(snatchTask.getTaskCode());
			if(null != snatchThread){
				snatchThread.destroy();
				webSnatchs.remove(snatchTask.getTaskCode());
			}
		}
		return 1;
	}
	
	
	
	private class SnatchThread extends Thread {

		protected Logger logger = Logger.getLogger(SnatchThread.class);
		
		private SnatchTask snatchTask;
		
		private SnatchService snatchDataImpl;
		
		private boolean flag = true;// 抓取线程运行和销毁的信号量
		
		@Override
		public void run() {
			while (flag) {
				try {
					Thread.sleep(getsleepTime());
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				ThirdInfo thirdInfo = null;
				try {
					long time = System.currentTimeMillis();
					// logger.info("获取帐号开始!");
					thirdInfo = AccountData.findThirdInfo(snatchTask
							.getWebCode());
					if (thirdInfo != null && flag) {
						String userName = thirdInfo.getLoginAccount().getUserName();
						thirdInfo.setSnatch(true);
						Long version = findVersion();
						if(null == version){
							addItemLog(snatchTask.getOnlyCode(), snatchTask.getItemOnlyCode(), "采集项："+snatchTask+"未取版本号,本次采集跳过！");
							continue;
						}
						snatchTask.setStatus(1);
						snatchTask.setStartTime(System.currentTimeMillis());
						snatchTask.setVersion(version);	//获取版本号
						addItemLog(snatchTask.getOnlyCode(), snatchTask.getItemOnlyCode(), "开始采集帐号："+userName);
						SnatchData snatchData = snatchDataImpl.getData(
								snatchTask, thirdInfo);
						int status = snatchDataImpl.inspData(snatchData);
						if(SnatchConstant.INSP_FAIL_DTAT_NULL == status){
							addItemLog(snatchTask.getOnlyCode(), snatchTask.getItemOnlyCode(), "采集数据为空，帐号为:"+userName);
							AccountData.logBack(thirdInfo);
							continue;
						}else if(SnatchConstant.INSP_FAIL_ACCOUNT_OUTLOGIN == status){
							addItemLog(snatchTask.getOnlyCode(), snatchTask.getItemOnlyCode(), "帐号被登出:"+userName);
							AccountData.logBack(thirdInfo);
							continue;
						}else if(SnatchConstant.INSP_FAIL_THIRD_MAINTEN == status){
							addItemLog(snatchTask.getOnlyCode(), snatchTask.getItemOnlyCode(), "内页正在维护中。。。");
							snatchTask.setPage(1);
							snatchTask.setStatus(-1);
							continue;
						}else if(SnatchConstant.INSP_FAIL_SNATCH_TIME == status){
							addItemLog(snatchTask.getOnlyCode(), snatchTask.getItemOnlyCode(), "采集发现第三方时间不正确,智能判断为旧数据,忽略此次采集数据。");
							continue;
						}
						//帐号使用完，重置状态等待其它系统使用
						if (thirdInfo != null) {
							thirdInfo.setSnatch(false);
							thirdInfo = null;
						}
						if (flag) {
							SnatchVersion snatchVersion = findSnatchVersion(snatchData);
							snatchVersion.setSnatchTime(System.currentTimeMillis() - time);
							for(int i=0;i<snatchData.getDatas().length;i++){
								String datastr = snatchData.getDatas()[i];
								if(datastr != null){
									String valuekey = CacheUtil.getSnatchDataKey(snatchTask.getOnlyCode(),snatchTask.getTaskCode(),i);
									cache.set(valuekey, datastr);
								}
							}
							snatchVersion.setVersion(snatchVersion.getVersion()+1);
							String versionkey = CacheUtil.getSnatchTactKey(snatchTask.getOnlyCode(),snatchTask.getTaskCode());
							cache.set(versionkey, snatchVersion);
						}
					}
					// logger.info(nodeTaskInput.getTaskCode()+" 版本号： "+ratioDataInput.getVersion()+" 采集总结束："+(System.currentTimeMillis()-time));
				} catch (Exception e) {
					logger.error("采集任务错误", e);
					loggerService.addItemLog(snatchTask.getOnlyCode(), snatchTask.getItemOnlyCode(), "采集任务错误");
				} finally {
					if (thirdInfo != null) {
						thirdInfo.setSnatch(false);
					}
				}
			}
			logger.info("采集任务结束" + snatchTask);

		}
		
		
		public Long getsleepTime(){
			boolean addtime = false;
			if(snatchTask.getStatus() !=1){
				addtime = true;
			}
			if(addtime)
				return snatchTask.getSleepTiem()+SnatchConstant.ASSISTA_SLEEP;
			return snatchTask.getSleepTiem();
		}
		
		public void init(SnatchTask snatchTask){
			this.snatchTask = snatchTask;
			snatchDataImpl = SnatchControl.getSnatchService(snatchTask.getWebCode());
		}
		
		public void destroy(){
			flag = false;
		}
		
		public void addItemLog(String webCode,String itemOnlyCode,String message){
			logger.info(message);
			loggerService.addItemLog(webCode, itemOnlyCode, message);
		}
		
		
		/**
		 * 根据采集数据获取版本号
		 * @param snatchData
		 * @return
		 */
		private SnatchVersion findSnatchVersion(SnatchData snatchData){
			SnatchVersion snatchVersion = new SnatchVersion();
			if(null == snatchData){
				snatchVersion.setVersion(0L);
			}else{
				snatchVersion.setVersion(snatchData.getSnatchTask().getVersion());
				snatchVersion.setSnatchTime(System.currentTimeMillis()-snatchData.getSnatchTask().getStartTime());
				snatchVersion.setThirdTime(snatchData.getSnatchTask().getThirdTime());
				snatchVersion.setThirdPage(snatchData.getSnatchTask().getPage());
				snatchVersion.setDataSize(snatchData.getDatas().length);
			}
			
			return snatchVersion;
		}
		
		/**
		 * 获取当前版本号
		 * @return
		 */
		private Long findVersion(){
			String vkey = CacheUtil.getVersionKey(snatchTask.getItemOnlyCode());
			Long verion = (Long)cache.get(vkey);
			if(null == verion){
				if(!cache.exists(vkey)){
					cache.set(vkey, 0L);
					return 0L;
				}else{
					return null;
				}
			}else{
				return verion;
			}
		}

	}

	
}
